import React, { useState, useEffect, useRef } from 'react';
import * as faceapi from 'face-api.js';
import { useDispatch, useSelector, } from 'react-redux';
import { changeflag } from "../../store/modules/count"
import { UploadOutline, loading } from 'antd-mobile-icons'
import store from '../../store';
import { Button, Space, Toast } from 'antd-mobile'


const FaceRecognition = () => {
    const displspatch = useDispatch()
    const videoRef = useRef(null);
    const canvasRef = useRef(null);
    const [isModelLoaded, setIsModelLoaded] = useState(false);
    const detectFacesFlag = useSelector(store => store.countSlice.detectFacesFlag)

    useEffect(() => {
        const loadModels = async () => {
            await Promise.all([
                faceapi.nets.tinyFaceDetector.loadFromUri('/models'),
                faceapi.nets.faceLandmark68Net.loadFromUri('/models'),
                faceapi.nets.faceRecognitionNet.loadFromUri('/models'),
                faceapi.nets.faceExpressionNet.loadFromUri('/models')
            ]);
            setIsModelLoaded(true);
        };

        loadModels();
    }, []);

    useEffect(() => {
        const startVideo = async () => {
            if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
                const stream = await navigator.mediaDevices.getUserMedia({ video: true });
                if (videoRef.current) {
                    videoRef.current.srcObject = stream;
                }
            }
        };

        startVideo();
    }, []);

    useEffect(() => {
        if (!isModelLoaded || !videoRef.current) return;

        const video = videoRef.current;
        const canvas = canvasRef.current;
        let intervalId;

        const detectFaces = async () => {
            const displaySize = { width: video.width, height: video.height };
            faceapi.matchDimensions(canvas, displaySize);
            intervalId = setInterval(async () => {
                const detections = await faceapi.detectAllFaces(video, new faceapi.TinyFaceDetectorOptions())
                    .withFaceLandmarks()
                    .withFaceExpressions();
                const resizedDetections = faceapi.resizeResults(detections, displaySize);
                canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height);
                faceapi.draw.drawDetections(canvas, resizedDetections);
                faceapi.draw.drawFaceLandmarks(canvas, resizedDetections);
                faceapi.draw.drawFaceExpressions(canvas, resizedDetections);
            }, 100);
        };

        if (detectFacesFlag) {
            detectFaces();
        } else {
            clearInterval(intervalId);
            canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height);
        }

        return () => {
            clearInterval(intervalId);
        };
    }, [isModelLoaded, detectFacesFlag]);
    const flags = () => {
        displspatch(changeflag(true))
        let time = 5
        let times = setInterval(() => {
            time--
            Toast.show({
                icon: 'loading',
                content: '加载中…',
            })
            if (time == 0) {
                displspatch(changeflag(false))
                Toast.show({
                    icon: 'success',
                    content: '支付成功',
                })
                clearInterval(times)
            }
        }, 1000)
    }
    return (
        <div>
            <video ref={videoRef} width="300" height="300" autoPlay muted style={{ display: detectFacesFlag ? "block" : "none", borderRadius: '50%' }} />

            <button onClick={() => { flags() }} style={{ color: "#fff", background: "chartreuse" ,border:"0",width:"100px",height:"50px"}}>立即支付</button>

        </div>
    );
};

export default FaceRecognition;